#
# npm install websocket (websocket-node.js)
# npm install underscore (underscore.js)
#

#
# Define
#
DEBUG = true
SERVER_HOST = null
SERVER_PORT = 3000


_und = require('underscore')

http_server = require('http').createServer((req, res) ->
  res.writeHeader 200,
    'Content-Type': 'text/html'

  res.end '<h1>Hello world</h1>'
)
http_server.listen SERVER_PORT, SERVER_HOST

#################
# server setup
#################
WebSocketServer = require('websocket').server
socket_server = new WebSocketServer({
      httpServer: http_server,
      autoAcceptConnections: false
  })

#
# socket: on try connection
#
socket_server.on 'request', (request)->
    console.log('Connection Request from ' + request.origin + ' : by ' + request.requestedProtocols)
    request.accept(null, null)

#
# socket: on connection established
#
socket_server.on 'connect', (client) ->
  console.log 'Connected : '

  client.on 'message', (message)->
    console.log message

    switch message.type
      when 'utf8'
        # JSON data
        client.sendUTF(message.utf8Data)
        console.log 'send utf'
      when 'binary'
        # binary data (Streaming PCM)
        console.log 'send binary'
        socket_server.connections.forEach (connection, i, ary)->
          connection.sendBytes(message.binaryData);

      else 
        console.log("Error : unknown message type #{message.type}")
